
package com.craterhill.java.ems.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public abstract class AbstractDao<T> extends JdbcDaoSupport {

	protected final static String FIELD_STATUS = "status";
	protected final static String FIELD_CREATED_BY = "created_by";
	protected final static String FIELD_CREATED_DATE = "created_date";
	protected final static String FIELD_MODIFIED_DATE = "modified_date";

	public final static String MONITER_FIELDS = ", obj." + FIELD_STATUS + ", obj." + FIELD_CREATED_BY + ", obj." + FIELD_CREATED_DATE + ", obj."
			+ FIELD_MODIFIED_DATE;

	public AbstractDao(final DataSource dataSource) {
		super.setDataSource(dataSource);
	}

	protected int save(final PreparedStatementCreator preparedStatementCreator) {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		int result = getJdbcTemplate().update(preparedStatementCreator, keyHolder);
		return result == 1 ? keyHolder.getKey().intValue() : -1;
	}

	protected boolean update(final PreparedStatementCreator preparedStatementCreator) {
		return getJdbcTemplate().update(preparedStatementCreator) != 0;
	}

	protected boolean batchOperation(final String deleteQuery, final BatchPreparedStatementSetter batchPreparedStatementSetter) {
		int[] result = getJdbcTemplate().batchUpdate(deleteQuery, batchPreparedStatementSetter);

		boolean isSucessed = false;
		for(int i : result){
			if(i == 1)
				isSucessed = true;
			else
				isSucessed = false;
		}
		return isSucessed;
	}

	protected T findSingleObject(final String query, final ResultSetExtractor<T> resultSetExtractor, final Object... filters) {
		return getJdbcTemplate().query(query, filters, resultSetExtractor);
	}

	protected List<T> findMultipleObject(final String query, final RowMapper<T> rowMapper, final Object... filters) {
		return getJdbcTemplate().query(query, filters, rowMapper);
	}
}
